﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.ServiceModel.Activation;

namespace WcfServiceHosted
{
	[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerSession)]
	[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
	public class MyDuplexService : IMyDuplexService
	{

		private static List<IMyDuplexCallback> m_list = new List<IMyDuplexCallback>();

		private static UserMessage MessageData = new UserMessage();

		public void Join(string userId)
		{
			IMyDuplexCallback callback = OperationContext.Current.
										GetCallbackChannel<IMyDuplexCallback>();
			if (!m_list.Contains(callback))
			{
				m_list.Add(callback);
			}
		}

		public void Leave(string userId)
		{
			IMyDuplexCallback callback = OperationContext.Current.
										GetCallbackChannel<IMyDuplexCallback>();
			if (m_list.Contains(callback))
			{
				m_list.Remove(callback);
			}
		}

		public void SendMessage(string userId, string message)
		{
			MessageData.MessageBody = message;
			MessageData.UserId = userId;

			CallClients();
		}

		public static void CallClients()
		{
			Action<IMyDuplexCallback> invoke = (callback) =>
			{
				callback.OnCallback(string.Format("{0} : {1}", MessageData.UserId, MessageData.MessageBody));
			};
			m_list.ForEach(invoke);
		}

	}
}
